package device

import (
	"net"
	"sync"
)

type AllowedIP struct {
	IP   *net.IPNet
	peer *Peer
}

type AllowedIPs struct {
	sync.RWMutex
	AllowedIPs []AllowedIP
}

func (allowedIPs *AllowedIPs) add(ip *net.IPNet, peer *Peer) {
	allowedIPs.Lock()
	defer allowedIPs.Unlock()
	// 去重
	for _, allowedIP := range allowedIPs.AllowedIPs {
		if allowedIP.IP.String() == ip.String() {
			return
		}
	}
	allowedIPs.AllowedIPs = append(allowedIPs.AllowedIPs, AllowedIP{
		IP:   ip,
		peer: peer,
	})
}

// 在 allowedIPs 中查找 ip 对应的 peer, 如果找不到则返回 nil, 匹配最精确的掩码
func (allowedIPs *AllowedIPs) find(ip net.IP) *Peer {
	allowedIPs.RLock()
	defer allowedIPs.RUnlock()

	var matchedPeer *Peer
	maxMaskSize := -1

	for _, allowedIP := range allowedIPs.AllowedIPs {
		// 检查 IP 是否在这个网段内
		if allowedIP.IP.Contains(ip) {
			// 获取当前网段的掩码长度
			maskSize, _ := allowedIP.IP.Mask.Size()

			// 如果找到更精确的匹配（掩码更长），则更新结果
			if maskSize > maxMaskSize {
				maxMaskSize = maskSize
				matchedPeer = allowedIP.peer
			}
		}
	}

	return matchedPeer
}
